﻿using IService;
using Microsoft.AspNetCore.Mvc;
using Model;

namespace WMS.Controllers
{
    public class SysAttachmentController : Controller
    {
        private readonly ISysAttachmentService _attachmentService;
        private readonly IWebHostEnvironment _env;  // 用于获取web根路径

        // 注入WebHostEnvironment以获取文件存储路径
        public SysAttachmentController(ISysAttachmentService attachmentService, IWebHostEnvironment env)
        {
            _attachmentService = attachmentService;
            _env = env;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 处理文件上传并保存附件信息
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UploadAttachment(List<IFormFile> files,
                                                         string createBy,
                                                         DateTime createTime,
                                                         string updateBy,
                                                         DateTime updateTime)
        {
            try
            {
                if (files == null || files.Count == 0)
                {
                    return Json(new { success = false, message = "未上传任何文件" });
                }

                // 1. 定义文件存储路径（wwwroot/attachments/yyyyMMdd）
                var uploadDir = Path.Combine(_env.WebRootPath, "attachments", DateTime.Now.ToString("yyyyMMdd"));
                if (!Directory.Exists(uploadDir))
                {
                    Directory.CreateDirectory(uploadDir);  // 不存在则创建目录
                }

                // 2. 处理每个文件并转换为DTO
                var attachmentList = new List<SysAttachmentDTO>();
                foreach (var file in files)
                {
                    // 生成唯一文件名（避免重复）
                    var uniqueFileName = $"{Guid.NewGuid()}_{Path.GetFileName(file.FileName)}";
                    var filePath = Path.Combine(uploadDir, uniqueFileName);

                    // 保存文件到服务器
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }

                    // 构建DTO对象
                    attachmentList.Add(new SysAttachmentDTO
                    {
                        AttachmentCode = GenerateAttachmentCode(),  // 生成附件编号
                        AttachmentAddress = filePath.Replace(_env.WebRootPath, "/attachments"),  // 存储相对路径
                        CreateBy = createBy,
                        CreateTime = createTime,
                        UpdateBy = updateBy,
                        UpdateTime = updateTime
                    });
                }

                // 3. 调用服务层批量保存到数据库
                var result = await _attachmentService.UploadAttachment(attachmentList);
                if (result > 0)
                {
                    return Json(new
                    {
                        success = true,
                        message = $"成功上传{result}个文件",
                        data = attachmentList  // 返回保存的附件信息给前端
                    });
                }
                return Json(new { success = false, message = "文件信息保存失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"上传失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 生成附件编号（业务规则：ATT+日期+随机数）
        /// </summary>
        private string GenerateAttachmentCode()
        {
            return $"ATT_{DateTime.Now:yyyyMMdd}_{Guid.NewGuid().ToString("N").Substring(0, 6)}";
        }
    }
}
